package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.Report;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员服务
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;

    //根据手机号查询会员信息
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //新增会员
    public void add(Member member) {
        //如果用户设置了密码，需要对密码进行md5加密
        String password = member.getPassword();
        if(password != null){
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    //根据月份查询会员数量
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCounts = new ArrayList<>();
        if(months != null && months.size() > 0){
            for (String month : months) {//2019.01
                String endTime = month + ".31";
                Integer memberCount = memberDao.findMemberCountBeforeDate(endTime);
                memberCounts.add(memberCount);
            }
        }
        return memberCounts;
    }

    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page page = memberDao.selectByCondition(queryString);
        List<Member> rows = page.getResult();
        long total = page.getTotal();
        return new PageResult(total,rows);
    }

    @Override
    public List<String> findManager() {
        List<String> manager = memberDao.findManager();
        return manager;
    }

    @Override
    public void delete(Integer id) {
        memberDao.deleteById(id);
    }

    @Override
    public void edit(Member member) {
        if (member!=null){
            memberDao.edit(member);
        }

    }

    @Override
    public Member findById(Integer id) {
        Member member = memberDao.findById(id);
        return member;
    }

    @Override
    public Map memberCount() {
        Map<String,Object> map = new HashMap<>();
        //获取会员总数
        Integer totalCount = memberDao.findMemberTotalCount();
        map.put("total",totalCount);
        //获取本月会员数
        try {
            String firstDay4ThisMonth = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth());
            Integer countAfterDate = orderDao.findOrderCountAfterDate(firstDay4ThisMonth);
            map.put("thisMothOrder",countAfterDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public PageResult getMemberReport(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        //查询全部的预约列表信息
        Page orderList = orderDao.findAll(queryString);
        List<Order> result = orderList.getResult();
        long total = orderList.getTotal();
        List<Map<String,Object>> rows = new ArrayList<>();
        //遍历
        for (Order order : result) {
            Map<String,Object> map = new HashMap<>();
            try {
                Integer orderId = order.getId();
                map.put("orderId",orderId);
                //获取体检时间
                String date = DateUtils.parseDate2String(order.getOrderDate(), "yyyy年MM月dd日");
                map.put("orderDate",date);
                //获取报告状态
                int status = order.getStatus();
                map.put("status",status);
                //获取到会员id
                Integer memberId = order.getMember_Id();
                map.put("memberId",memberId);
                //根据会员id获取到相关信息
                Member member = memberDao.findById(memberId);
                //获取档案号
                String fileNumber = member.getFileNumber();
                map.put("fileNumber",fileNumber);
                //获取到姓名
                String name = member.getName();
                map.put("name",name);
                //获取到手机号码
                String phoneNumber = member.getPhoneNumber();
                map.put("phoneNumber",phoneNumber);
                //拿到套餐id,获取套餐名
                Integer setmealId = order.getSetmeal_Id();
                Setmeal setmeal = setmealDao.findById4Detail(setmealId);
                String setMeal = setmeal.getName();
                map.put("setMeal",setMeal);
                rows.add(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new PageResult(total, rows);
    }

    @Override
    public void uploadReport(Map map) {
        //向report表中存数据,包括orderId,fileName
        String imgName = (String) map.get("imgName");
        Integer orderId = (Integer) map.get("orderId");
        Report report = new Report(imgName, orderId);
        memberDao.addReport(report);
        //根据orderId,ReportId建立中间表关系
        Integer memberId = (Integer) map.get("memberId");
        int reportId = report.getId();
        HashMap<String,Integer> hashMap = new HashMap<>();
        hashMap.put("memberId",memberId);
        hashMap.put("reportId",reportId);
        //添加中间表关系
        memberDao.addRelaByIds(hashMap);
        //完成数据库操作后需要将文件名称保存到redis
        jedisPool.getResource().sadd(RedisConstant.MEMBER_FILE_DB_REPORT,(String) map.get("imgName"));
        //将order表中status改成1
        orderDao.editStatusUp(orderId);
    }

    @Override
    public void deleteReport(Integer memberId,Integer orderId) {
        System.out.println("memberId = " + memberId);
        System.out.println("orderId = " + orderId);
        //首先删除中间表关系
        memberDao.deleteRelaByIds(memberId,orderId);
        //删除体检报告表
        memberDao.deleteReport(orderId);
        //将order表中的status改成0
        orderDao.editStatusDown(orderId);
    }

    @Override
    public List<String> findAll() {
        return memberDao.findMemberName();
    }
}
